package com.steakliu.sun.server;

import com.steakliu.sun.common.thread.ServerConcurrentThreadPool;
import com.steakliu.sun.invoker.api.Invoker;
import com.steakliu.sun.registry.api.RegistryConfig;
import com.steakliu.sun.registry.api.RegistryService;
import com.steakliu.sun.scanner.SunServiceScanner;
import com.steakliu.sun.server.api.ServerConfig;
import com.steakliu.sun.server.api.ServerLocalServiceCaches;
import com.steakliu.sun.server.netty.NettyServer;
import com.steakliu.sun.spi.loader.ExtensionLoader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;

/**
 * 功能说明： 原生服务端启动入口
 * <p>
 * Original @Author: steakliu-刘牌, 2023-01-08  00:35
 * <p>
 * Copyright (C)2020-2022  steakliu All rights reserved.
 */
public class NativeNettyServer {

    private final Logger logger = LoggerFactory.getLogger(NativeNettyServer.class);

    public void start(ServerConfig serverConfig) throws Exception {
        //构建注册中心
        RegistryService registryService = ExtensionLoader.getExtension(RegistryService.class, serverConfig.getRegistryType());
        registryService.init(new RegistryConfig(serverConfig.getRegistryAddress()));
        //构建反射调用
        Invoker invoker = ExtensionLoader.getExtension(Invoker.class, serverConfig.getReflect());
        //扫描服务并注册到注册中心和添加到本地缓存
        Map<String, ServerLocalServiceCaches> cacheServices = SunServiceScanner.scanner(serverConfig.getHost(), serverConfig.getPort(), serverConfig.getScanPackage(), registryService);
        //初始化并发线程池
        ServerConcurrentThreadPool serverConcurrentThreadPool = ServerConcurrentThreadPool.getInstance(serverConfig.getConcurrentCorePoolSize(), serverConfig.getConcurrentMaximumPoolSize());
        //启动Netty服务端
        NettyServer nettyServer = new NettyServer(cacheServices, invoker, serverConfig, serverConcurrentThreadPool);
        nettyServer.startServer();
    }
}
